package com.fqgj.sentry.biz.pc;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.sentry.biz.pc.vo.policyset.PolicySetResultVo;
import com.fqgj.sentry.biz.pc.vo.policyset.PolicySetVo;
import com.fqgj.sentry.controller.pc.request.AddPolicySetVo;
import com.fqgj.sentry.controller.pc.request.UpdatePolicySetVo;
import com.fqgj.sentry.manage.entity.McApplicationEntity;
import com.fqgj.sentry.manage.service.ApplicationService;
import com.fqgj.sentry.policy.client.ExecuteResultService;
import com.fqgj.sentry.policy.client.PolicySetService;
import com.fqgj.sentry.policy.dao.PcEventDao;
import com.fqgj.sentry.policy.entity.PcEventEntity;
import com.fqgj.sentry.policy.entity.PcExecuteResultEntity;
import com.fqgj.sentry.policy.entity.PcPolicySetsEntity;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by ykpbean kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2017-07-26 下午2:06
 */

@Component
public class PolicySetBusiness {
    @Autowired
    private PolicySetService policySetService;
    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private ExecuteResultService executeResultService;

    @Autowired
    private PcEventDao pcEventDao;


    public Boolean addPolicySet(AddPolicySetVo addPolicySetVo) {
        PcPolicySetsEntity pcPolicySetsEntity = new PcPolicySetsEntity();
        BeanUtils.copyProperties(addPolicySetVo, pcPolicySetsEntity);

        List<String> moduleCodes = addPolicySetVo.getModuleCodes();
        String moduleCodesStr = JSON.toJSONString(moduleCodes);
        pcPolicySetsEntity.setModulesCode(moduleCodesStr);
        policySetService.insertPolicySet(pcPolicySetsEntity);
        return true;
    }

    public Boolean deletePolicySet(Long id) {
        return policySetService.deletePolicySet(id);
    }

    public Boolean updatePolicySet(UpdatePolicySetVo updatePolicySetVo) {
        PcPolicySetsEntity policySetsEntity = policySetService.selectOneById(updatePolicySetVo.getId());
        policySetsEntity.setName(updatePolicySetVo.getName());
        policySetsEntity.setInfo(updatePolicySetVo.getInfo());
        policySetsEntity.setModulesCode(JSON.toJSONString(updatePolicySetVo.getModuleKeys()));
        return policySetService.updatePolicySet(policySetsEntity);
    }

    public List<PolicySetVo> queryPolicySetForPage(String appCode, Long merchantId) {
        McApplicationEntity applicationEntity = applicationService.selectByMerchantIdAndAppCode(merchantId, appCode);
        List<PcPolicySetsEntity> policySetsEntityList = policySetService.selectList(applicationEntity.getId());

        Map<Long, String> eventIdAndNameMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(policySetsEntityList)) {
            List<Long> eventIds = new ArrayList<>();
            policySetsEntityList.forEach(d -> {
                eventIds.add(d.getEventId());
            });

            List<PcEventEntity> pcEventEntities = pcEventDao.selectListByEventIds(eventIds);
            pcEventEntities.forEach(p -> {
                eventIdAndNameMap.put(p.getId(), p.getCode());
            });
        }


        List<PolicySetVo> policySetVoList = new ArrayList<>();
        for (PcPolicySetsEntity entity : policySetsEntityList) {
            PolicySetVo policySetVo = new PolicySetVo();
            BeanUtils.copyProperties(entity, policySetVo);
            policySetVo.setEventKey(eventIdAndNameMap.get(entity.getEventId()));

            if (StringUtils.isNotEmpty(entity.getModulesCode())) {
                List<String> moduleKeys = new ArrayList<>();
                List<Any> anies = JsonIterator.deserialize(entity.getModulesCode()).asList();
                anies.forEach(a -> {
                    moduleKeys.add(a.toString());
                });
                policySetVo.setModuleKeys(moduleKeys);
            }

            policySetVoList.add(policySetVo);
        }
        return policySetVoList;
    }

    /**
     * 策略集 结果查询
     *
     * @param policySetsId
     * @return
     */
    public PolicySetResultVo queryPolicySetResult(Long policySetsId) {
        PcPolicySetsEntity policySetsEntity = policySetService.selectOneById(policySetsId);
        List<PcExecuteResultEntity> resultEntityList = executeResultService.selectExecuteResultList(policySetsId);
        PolicySetResultVo policySetResultVo = new PolicySetResultVo();
        List<PolicySetResultVo.ResultItem> resultList = new ArrayList<>();
        for (PcExecuteResultEntity resultEntity : resultEntityList) {
            PolicySetResultVo.ResultItem resultItem = new PolicySetResultVo.ResultItem();
            resultItem.setResultId(resultEntity.getId())
                    .setResult(resultEntity.getResult())
                    .setResultDesc(resultEntity.getResultDesc())
                    .setResultPriority(resultEntity.getLevel())
                    .setResultType(resultEntity.getResultType())
                    .setType(resultEntity.getType());
            resultList.add(resultItem);
        }
        policySetResultVo.setPolicySetsId(policySetsId)
                .setMatchingType(policySetsEntity.getMatchingType())
                .setResultList(resultList);
        return policySetResultVo;
    }

    /**
     * 策略集 结果修改
     *
     * @param policySetResultVo
     * @return
     */
    public void policySetResultUpdate(PolicySetResultVo policySetResultVo) {
        //修改匹配 类型
        PcPolicySetsEntity policySetsEntity = policySetService.selectOneById(policySetResultVo.getPolicySetsId());
        if (policySetsEntity.getMatchingType() != policySetResultVo.getMatchingType()) {
            policySetsEntity.setMatchingType(policySetResultVo.getMatchingType());
            policySetService.updatePolicySet(policySetsEntity);
        }
        //修改 执行结果
        List<PolicySetResultVo.ResultItem> resultList = policySetResultVo.getResultList();
        for (PolicySetResultVo.ResultItem resultItem : resultList) {
            if (resultItem.getResultId() != null) {
                PcExecuteResultEntity executeResultEntity = executeResultService.findByExecutorResultId(resultItem.getResultId());
                executeResultEntity.setResult(resultItem.getResult())
                        .setResultDesc(resultItem.getResultDesc())
                        .setLevel(resultItem.getResultPriority())
                        .setType(resultItem.getType())
                        .setResultType(resultItem.getResultType())
                        .setDeleted(resultItem.getDelete());
                executeResultService.updateExecuteResult(executeResultEntity);
            } else {
                PcExecuteResultEntity entity = new PcExecuteResultEntity();
                entity.setPolicySetsId(policySetResultVo.getPolicySetsId())
                        .setResult(resultItem.getResult())
                        .setResultDesc(resultItem.getResultDesc())
                        .setLevel(resultItem.getResultPriority())
                        .setType(resultItem.getType())
                        .setResultType(resultItem.getResultType())
                        .setGmtCreate(new Date())
                        .setDeleted(resultItem.getDelete());
                executeResultService.insertExecuteResult(entity);
            }
        }
    }
}
